package com.springboot.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.springboot.biz.ItemBiz;
import com.springboot.biz.PipeBiz;
import com.springboot.biz.ProjectBiz;
import com.springboot.entity.Item;
import com.springboot.entity.Pipe;
import com.springboot.entity.Project;
import com.springboot.util.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class FileInfoController {

    @Value(value = "${myfile}")
    private String path;

    @Resource
    private ProjectBiz projectBiz;
    @Resource
    private PipeBiz pipeBiz;
    @Resource
    private ItemBiz itemBiz;
    @Resource
    private HelperDOC helperDOC;
    @Resource
    private HelperMDB helperMDB;
    @Resource
    private HelperPDF helperPDF;

    /**
     * 下载项目文档
     */
    @RequestMapping(value = "/download")
    public void download(int id, HttpServletResponse response) throws IOException {
        Project project = projectBiz.findInfoProject(id, null);
        if (StringUtils.isEmpty(project))
            return; // 查询结果为空
        String srcPath = path + "/report/";
        String zipPath = path + "/compre/";
        String name = AppHelper.UUIDCode();
        File report = new File(srcPath + name + "/report/");
        File vedio = new File(srcPath + name + "/video/");
        File data = new File(srcPath + name + "/data/");
        File compre = new File(zipPath + name);
        compre.mkdirs();
        report.mkdirs();
        vedio.mkdirs();
        data.mkdirs();

        List<Pipe> pipes = pipeBiz.findListPipe(project);
        assert pipes != null;

        for (Pipe pipe : pipes) { // 计算管道分数
            pipe.setItems(itemBiz.findListItem(pipe));
            Computes.computePipe(pipe, project.getStandard());
        }
        project.setPipes(pipes);

        String file = srcPath + name + "/" + project.getDate() + "_" + project.getName();
        AppHelper.convert(project, data.getPath() + "/" + project.getName() + ".xml");

        Map<String, Object> map = new HashMap<>(2);
        map.put("pipes", pipes);
        List<Item> items = pipes.stream().flatMap(pipe -> pipe.getItems().stream()).collect(Collectors.toList());
        map.put("items", items);

        File pipeTemp = ResourceUtils.getFile("classpath:pipeTemp.xlsx");
        TemplateExportParams params = new TemplateExportParams(pipeTemp.getPath(), true);
        params.setSheetName(new String[]{"PIPE", "ITEM"});
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        OutputStream stream = new FileOutputStream(data.getPath() + "/" + project.getName() + ".xlsx");
        workbook.write(stream);

        helperPDF.initPDF(project, file + "_CCTV.pdf");
        // helperMDB.initMDB(project, srcPath + name + "/");
        helperDOC.initDOC(project, srcPath + name + "/");

        String fileName = project.getDate() + "_" + project.getName();
        File zipFile = ZipFileHelper.toZip(srcPath + name, zipPath + name, fileName);
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName + ".zip");
        response.setContentType("application/force-download");

        int len = -1;
        byte[] buffer = new byte[1024];
        InputStream fstream = null;
        InputStream bstream = null;
        OutputStream outputStream = null;
        try {
            fstream = new FileInputStream(zipFile.getPath());
            bstream = new BufferedInputStream(fstream);
            outputStream = response.getOutputStream();
            while ((len = bstream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null)
                    outputStream.close();
                if (bstream != null)
                    bstream.close();
                if (fstream != null)
                    fstream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
